﻿import altair as alt
import pandas as pd
import numpy as np
from vega_datasets import data

# 加载示例数据
cars = data.cars()

# 创建交互式选择器
brush = alt.selection_interval()

# 创建散点图
scatter = alt.Chart(cars).mark_point().encode(
    x=alt.X('Horsepower:Q', title='马力'),
    y=alt.Y('Miles_per_Gallon:Q', title='每加仑英里数'),
    color=alt.condition(brush, 'Origin:N', alt.value('lightgray')),
    tooltip=['Name', 'Horsepower', 'Miles_per_Gallon', 'Origin']
).add_selection(
    brush
).properties(
    width=400,
    height=300,
    title='汽车马力与燃油效率关系'
)

# 创建柱状图
bar = alt.Chart(cars).mark_bar().encode(
    x=alt.X('count()', title='数量'),
    y=alt.Y('Origin:N', title='产地'),
    color=alt.condition(brush, 'Origin:N', alt.value('lightgray'))
).add_selection(
    brush
).properties(
    width=200,
    height=300,
    title='汽车产地分布'
)

# 创建直方图
histogram = alt.Chart(cars).mark_bar().encode(
    x=alt.X('Horsepower:Q', bin=alt.Bin(maxbins=20), title='马力'),
    y=alt.Y('count()', title='数量'),
    color=alt.condition(brush, 'Origin:N', alt.value('lightgray'))
).add_selection(
    brush
).properties(
    width=400,
    height=200,
    title='马力分布'
)

# 组合图表
dashboard = alt.vconcat(
    alt.hconcat(scatter, bar),
    histogram
).configure_view(
    strokeWidth=0
).configure_axis(
    labelFontSize=12,
    titleFontSize=14
).configure_title(
    fontSize=16,
    anchor='start'
)

# 显示图表
dashboard

# 保存图表
dashboard.save('altair_dashboard.html')






# 使用 vega_datasets 中的数据集
stocks = data.stocks()
iris = data.iris()
unemployment = data.unemployment()

# 股票数据示例
stock_chart = alt.Chart(stocks).mark_line().encode(
    x='date:T',
    y='price:Q',
    color='symbol:N'
).properties(
    width=600,
    height=300
)

# 鸢尾花数据示例
iris_chart = alt.Chart(iris).mark_point().encode(
    x='petalLength:Q',
    y='petalWidth:Q',
    color='species:N'
)

# 失业率数据示例
unemployment_chart = alt.Chart(unemployment).mark_rect().encode(
    x='year:O',
    y='month:O',
    color='rate:Q'
)





